<template>
  <view class="my-settle-container">
    <view class="radio">
      <radio
        color="#fa5151"
        :checked="getAllSelectState"
        @click="toggel"
      ></radio
      >全选</view
    >
    <view>
      合计：<text class="amount">￥{{ getSelectAmount }}</text>
    </view>
    <view
      class="btn-settle"
      :style="{ backgroundColor: getSelectTotal === 0 ? '#bdbdbd' : '#c00000' }"
      @click="settle"
    >
      <text v-if="getSelectTotal === 0">结算</text>
      <text v-else>结算({{ getSelectTotal }})</text>
    </view>
  </view>
</template>

<script>
// 导入vuex辅助函数
import { mapGetters, mapMutations } from "vuex";

export default {
  data() {
    return {
      // 倒计时
      time: 3,
      // 倒计时的状态默认为false
      isCountDown: false,
    };
  },
  computed: {
    ...mapGetters("cart", [
      "getSelectAmount",
      "getSelectTotal",
      "getAllSelectState",
      "getCartList",
    ]),
    ...mapGetters("user", ["getAddress", "getToken", "getAddressStr"]),
  },
  methods: {
    ...mapMutations("cart", ["updateAllGoodsState"]),
    ...mapMutations("user", ["setRedirectUrl"]),
    // 全选
    toggel() {
      this.updateAllGoodsState(!this.getSelectTotal);
    },
    // 结算
    settle() {
      // 判断是否选购了商品
      if (this.getSelectTotal === 0) {
        uni.showToast({
          title: "请勾选所需结算的商品 !",
          icon: "none",
        });
        return;
      }
      // 判断是否有收货地址
      if (!this.getAddress) {
        uni.showToast({
          title: "请填写收货地址 !",
          icon: "none",
        });
        return;
      }
      // 判断用户是否登入
      // if (!this.getToken) {
      //   if (this.isCountDown) return;
      //   // 开始倒计时
      //   this.isCountDown = true;
      //   uni.showToast({
      //     title: `请先登录 ! ${this.time} 秒之后跳转到登入页`,
      //     icon: "none",
      //     disabled: 1000,
      //   });
      //   this.timer = setInterval(() => {
      //     if (this.time <= 1) {
      //       clearInterval(this.timer);
      //       (this.time = 3), (this.isCountDown = false);

      //       uni.switchTab({
      //         url: "/pages/my/index",
      //         success: () => {
      //           this.setRedirectUrl("/pages/cart/index");
      //         },
      //       });

      //       return;
      //     }
      //     this.time--;
      //     uni.showToast({
      //       title: `请先登录 ! ${this.time} 秒之后跳转到登入页`,
      //       icon: "none",
      //       disabled: 1000,
      //     });
      //   }, 1000);

      //   return;
      // }
      this.orderAndPay();
    },
    // 下单
    async orderAndPay() {
      const params = {
        order_price: this.getSelectAmount,
        consignee_addr: `${this.getAddressStr} ${this.getAddress.userName}  ${this.getAddress.telNumber}`,
        goods: this.getCartList
          .filter((item) => item.goods_state)
          .map(({ goods_id, goods_number, goods_price }) => ({
            goods_id,
            goods_number,
            goods_price,
          })),
      };
      console.log(params);
      const res = await uni.$request({
        url: "my/orders/create",
        method: "POST",
        data: params,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        uni.showToast({
          title: "创建订单失败",
          icon: "error",
        });
        return;
      }
      const { order_number } = res.message;
      // 支付
      const res2 = await uni.$request({
        url: "my/orders/req_unifiedorder",
        method: "POST",
        data() {
          return {
            order_number,
          };
        },
      });
      console.log(res2);

      if (res2.meta.status !== 200) {
        uni.showToast({
          title: "请求支付失败",
          icon: "error",
        });
        return;
      }
      uni.requestPayment({
        ...res2.message.pay,
        success: async (obj) => {
          const res3 = await uni.$request({
            url: "my/orders/chkOrder",
            method: "POST",
            data: {
              order_number,
            },
          });
          if (res3.meta.status === 200) {
            uni.showToast({
              title: res3.message,
              duration: 500,
              success: () => {
                setTimeout(() => {
                  uni.navigateTo({
                    url: "/subpkg/pay-result/index",
                  });
                }, 500);
              },
            });
          }
        },
        fill: ({ errMsg }) => {
          if (errMsg === "requestPayment:fail cancal") {
            uni.showToast({
              title: "取消支付成功",
              icon: "error",
            });
          } else {
            uni.showToast({
              title: "支付失败,请联系客服",
              icon: "none",
            });
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.my-settle-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  // 将背景色从 cyan 改为 white
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 5px;
  font-size: 14px;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount {
    color: #c00000;
  }

  .btn-settle {
    height: 50px;
    min-width: 100px;
    // background-color: #c00000;
    color: white;
    line-height: 50px;
    text-align: center;
    padding: 0 10px;
  }
}
</style>
